package com.book.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/searchid")
public class searchid extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String idbook = req.getParameter("id");
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/library?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true","root","1234");
            ps = conn.prepareStatement("select * from book where id = " + idbook);
            rs = ps.executeQuery();
            List<Book> bookList = new ArrayList();
            while(rs.next()){
                Book book = new Book();
                book.setId(rs.getString(1));
                book.setName(rs.getString(2));
                book.setAuthor(rs.getString(3));
                book.setType(rs.getString(4));
                book.setPhoto(rs.getString(5));
                book.setContent(rs.getString(6));
                book.setBorrow(rs.getString(7));
                bookList.add(book);
            }
            resp.setContentType("text/html");
            req.setAttribute("bookList", bookList);
            req.getRequestDispatcher("/search1.jsp").forward(req, resp);
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs != null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}